package com.lanjiu.lib.business.work;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 线程池工厂，负责文件传输任务
 * @author: Panwei
 * @date: 2019/11/2 9:36
 */
public class FileTransmissionExecutor {

    private ExecutorService mExecutorService;  // 管理线程组

    /**
     * 初始化线程池
     */
    public synchronized void initFileTransmissionExecutor() {
        destroyFileTransmissionExecutor();
        mExecutorService = Executors.newCachedThreadPool();
    }

    /**
     * 执行任务
     *
     * @param r
     */
    public void execFileTransmissionTask(Runnable r) {
        if (mExecutorService == null) {
            initFileTransmissionExecutor();
        }
        mExecutorService.execute(r);
    }

    /**
     * 释放线程池
     */
    public synchronized void destroyFileTransmissionExecutor() {
        if (mExecutorService != null) {
            try {
                mExecutorService.shutdownNow();
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                mExecutorService = null;
            }
        }
    }

    public boolean isShutdown() {
        if (mExecutorService != null) {
            return mExecutorService.isShutdown();
        }
        return true;
    }
}
